/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.

package com.bifrost.job;

import com.alibaba.fastjson.JSON;
import com.bifrost.common.util.SpringContextUtils;
import com.bifrost.constant.ScheduleStatus;
import com.bifrost.entity.ScheduleJob;
import com.bifrost.entity.ScheduleJobLog;
import com.bifrost.service.ScheduleJobLogService;
import org.apache.commons.lang.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author joewee
 * @version 1.0.0
 * @Date 2017/11/6 15:32
@DisallowConcurrentExecution
public class ScheduleJobBean extends QuartzJobBean {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private ExecutorService service = Executors.newSingleThreadExecutor();

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        String jsonJob = context.getMergedJobDataMap().getString(ScheduleJob.JOB_PARAM_KEY);
        ScheduleJob scheduleJob = JSON.parseObject(jsonJob, ScheduleJob.class);

        //获取spring bean
        ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtils.getBean("scheduleJobLogService");

        //数据库保存执行记录
        ScheduleJobLog log = new ScheduleJobLog();
        log.setJobId(scheduleJob);
        log.setBeanName(scheduleJob.getBeanName());
        log.setMethodName(scheduleJob.getMethodName());
        log.setParams(scheduleJob.getParams());
        log.setCreateTime(new Date());

        //任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            //执行任务
            if (logger.isDebugEnabled()) {
                logger.debug("开执行任务ID：{}-{}{}" + scheduleJob.getId(), scheduleJob.getBeanName(), scheduleJob.getRemark());
            }
            ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(),
                    scheduleJob.getMethodName(), scheduleJob.getParams());
            Future<?> future = service.submit(task);

            future.get();

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes((int) times);
            //任务状态    0：成功    1：失败
            log.setStatus(ScheduleStatus.NORMAL.getValue());
            if (logger.isInfoEnabled()) {
                logger.info("任务ID：{}-{}{}执行完毕,总共耗时：{}毫秒", scheduleJob.getId(), scheduleJob.getBeanName(), scheduleJob.getRemark(), times);
            }
        } catch (Exception e) {
            logger.error("任务ID:" + scheduleJob.getId() + "执行失败", e);

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes((int) times);

            //任务状态    0：成功    1：失败
            log.setStatus(ScheduleStatus.PAUSE.getValue());
            log.setError(StringUtils.substring(e.toString(), 0, 2000));
            scheduleJobLogService.save(log);
        } finally {
            //logger.info(JSON.toJSONString(log));
        }
    }
}
*/